//
//  HMTabBar.swift
//  WeiBoXR
//
//  Created by acer on 16/9/19.
//  Copyright © 2016年 acer. All rights reserved.
//

import UIKit
protocol HMTabBarDelegate: NSObjectProtocol {
    func didSelectedAddButton()
}
class HMTabBar: UITabBar {

    var addButtonClosure: (()->())?
    
    var hmDelegate: HMTabBarDelegate?
    
    private lazy var addbutton: UIButton = {
        
        //tabbar中间的加号
        let button = UIButton()
        button.addTarget(self , action: #selector(buttonClick), for: .touchUpInside)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        button.sizeToFit()
        
        return button
    }()
    
    //@objc告诉编译器使用oc的方式调用代码
    @objc private func buttonClick() {
        
        addButtonClosure?()
        //如果闭包有值就执行代理方法
        hmDelegate?.didSelectedAddButton()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
//使用xib或SB创建对象的时候，会走这个方法，上面的是提示不支持xib，使用下面的代码解决了不支持xib的问题
    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")

        super.init(coder: aDecoder)
        setupUI()
    }
    
    private func setupUI() {
        
        backgroundImage = UIImage(named: "tabbar_background")
        backgroundColor = UIColor.white
        addSubview(addbutton)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        addbutton.centerX = width * 0.5
        addbutton.centerY = height * 0.5
        
        let itemWidth = width / 5

        var index = 0
        for value in subviews
        {
            if value.isKind(of: NSClassFromString("UITabBarButton")!)
            {
                value.width = itemWidth
                value.x = CGFloat(index) * itemWidth
                index += 1
                if index == 2 {
                    index += 1
                }
            }
        }
    }
}
